import { AddressInfo } from 'net'
import { Plugin } from 'vite'
import fs from 'fs'
import { spawn } from 'child_process'

async function buildEsbuildBackground() {
  // build background.js
  require('esbuild').buildSync({
    entryPoints: ['electron/background.ts'],
    outfile: 'dist/background.js',
    platform: 'node',
    target: 'node22',
    bundle: true,
    external: ['electron'],
  })

  require('esbuild').buildSync({
    entryPoints: ['electron/preload/index.ts'],
    outfile: 'dist/preload.js',
    platform: 'node',
    target: 'node22',
    bundle: true,
    external: ['electron'],
  })
}

export const ElectronDevPlugins = (): Plugin => {
  return {
    name: 'electron-dev',
    async configureServer(server) {
      buildEsbuildBackground()
      server.httpServer?.once('listening', () => {
        const addressInfo = server.httpServer?.address() as AddressInfo
        const IP = 'http://localhost:' + addressInfo.port
        // package.json commonjs
        let ElectronChind = spawn(require('electron'), ['dist/background.js', IP])

        // const nestServer = spawn('npm', ['run', 'start:dev'], { cwd: 'server' })

        fs.watchFile('electron/background.ts', () => {
          ElectronChind.kill()
          buildEsbuildBackground()

          ElectronChind = spawn(require('electron'), ['dist/background.js', IP])

          ElectronChind.stdout.on('data', (data) => {
            console.log(`stdout: ${data}`)
          })

          ElectronChind.on('close', (code) => {
            console.log(`child process exited with code ${code}`)
          })
        })
        console.log(IP)
      })
    },
  }
}
